import React from "react";
import style from "./style.module.css";
export class Item extends React.Component {
  state = {
    show: false,
    activeIndex: -1,
  };
  show() {
    this.setState({
      show: true,
    });
  }
  changeActiveIndex(i) {
    const { name, option } = this.props;
    this.setState({
      activeIndex: i,
      show: false,
    });

    this.props.change({ [name]: option[i].value });
  }
  render() {
    const { title, option } = this.props;
    const { activeIndex, show } = this.state;
    return (
      <div>
        <span onClick={() => this.show()}>
          {option[activeIndex]?.text || title}
        </span>
        <div
          className={style.dialog}
          style={{ display: show ? "block" : "none" }}
        >
          <div className={style.content}>
            <ul>
              {option.map((v, i) => {
                return (
                  <li
                    onClick={() => this.changeActiveIndex(i)}
                    key={i}
                    className={i === activeIndex ? style.active : ""}
                  >
                    {v.text}
                  </li>
                );
              })}
            </ul>
          </div>
        </div>
      </div>
    );
  }
}

class DropDownMenu extends React.Component {
  state = {
    value: {},
  };
  changeName(obj) {
    this.setState({
      value: {
        ...this.state.value,
        ...obj,
      },
    });
    this.props.onChange({
      ...this.state.value,
      ...obj,
    });
  }
  render() {
    const { children } = this.props;
    return (
      <div>
        <div className={style.title}>
          {children.map((v, i) => {
            const { title = "请选择", option = [], name } = v.props;
            return (
              <Item
                key={i}
                title={title}
                option={option}
                name={name}
                change={(v) => this.changeName(v)}
              ></Item>
            );
          })}
        </div>
      </div>
    );
  }

  static Item = Item;
}

export default DropDownMenu;
